import shutil
import time


from requests import Session
from sqlalchemy import func, text

from models.booking_model import Booking
from models.consultation_model import Consultation
from models.medicine_model import Medicine
from models.payment_model import Payment
from models.prescription_model import Prescription
from models.user_models import Account
from services.datetime_service import now_time


def get_system_status_service(db: Session):
    start_time = time.time()

    user_count = db.query(func.count(Account.ID)).scalar()
    today = now_time().date()
    booking_today_count = db.query(func.count(Booking.ID)).filter(Booking.book_date == today).scalar()

    # ✅ 新增：获取总挂号数
    booking_total_count = db.query(func.count(Booking.ID)).scalar()

    try:
        db.execute(text("SELECT 1"))
        db_status = "连接正常"
    except Exception as e:
        db_status = f"连接失败: {str(e)}"

    latency_ms = round((time.time() - start_time) * 1000, 2)
    total, used, free = shutil.disk_usage("/")
    storage_usage_percent = round((used / total) * 100, 2)

    payment_count = db.query(func.count(Payment.ID)).scalar()
    medicine_count = db.query(func.count(Medicine.ID)).scalar()
    consultation_count = db.query(func.count(Consultation.ID)).scalar()
    prescription_count = db.query(func.count(Prescription.ID)).scalar()

    return {
        "user_count": user_count,
        "today": today.isoformat(),
        "booking_today_count": booking_today_count,
        "booking_total_count": booking_total_count,
        "server_status": "正常",
        "database_status": db_status,
        "api_latency_ms": latency_ms,
        "storage_usage_percent": storage_usage_percent,
        "payment_count": payment_count,
        "medicine_count": medicine_count,
        "consultation_count": consultation_count,
        "prescription_count": prescription_count
    }